<template>
  <div>
    <!-- <a-form ref="formRef" :model="searchForm">
      <a-row>
        <a-col :span="6" :offset="1">
          <a-form-item label="管理员" name="realName">
            <a-input v-model:value="searchForm.realName" placeholder="请输入搜索内容"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6" :offset="1">
          <a-form-item label="岗位" name="jobName">
            <a-input v-model:value="searchForm.jobName" placeholder="请输入搜索内容"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6" :offset="1">
          <a-form-item label="账号" name="account">
            <a-input v-model:value="searchForm.account" placeholder="请输入搜索内容"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6" :offset="1">
          <a-form-item label="角色权限" name="roleId">
            <a-select ref="select" v-model:value="searchForm.roleId" @change="handleChange" placeholder="请选择角色权限">
              <a-select-option v-for="item in roleList" :value="item.id" :key="item.id">{{ item.name }} </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="4" :offset="1">
          <a-button type="primary" @click="search" class="d-a-center">搜索</a-button>
        </a-col>
      </a-row>
    </a-form>
    <a-divider></a-divider> -->
    <div class="df">
      <a-button
        type="primary"
        size="medium"
        style="margin-bottom: 20px; margin-right: 20px"
        @click="addDep"
        v-has="{ a: $route, b: 2 }"
        class="d-a-center"
        >新增部门</a-button
      >
      <a-button type="primary" size="medium" style="margin-bottom: 20px" @click="add" v-has="{ a: $route, b: 2 }" class="d-a-center"
        >新增管理员
      </a-button>
    </div>
    <a-row>
      <a-col :span="4" :offset="1">
        <div class="dep_wrap">
          <div v-for="item in deparmentList" :class="{ active: item.id == activeDep }" :key="item.id" @click="handleActive(item.id)">
            <div class="dep">
              {{ item.departmentName }}
              <span v-has="{ a: $route, b: 2 }">
                <EditOutlined style="margin-left: 10px" @click="handleEditDep(item)" />
                <MinusCircleOutlined style="margin-left: 10px" @click="handleDeleteDep(item.id)" />
              </span>
            </div>
          </div>
        </div>
      </a-col>
      <a-col :span="16" :offset="1">
        <a-table
          :columns="columns"
          :data-source="list"
          bordered
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
          :row-selection="rowSelection"
        >
          <template #isDele="{ record }">
            <div>{{ record.isDele == 0 ? '启用' : '禁用' }}</div>
          </template>
          <template #operation="{ record }">
            <a-button type="link" @click="edit(record.id)" v-has="{ a: $route, b: 2 }">编辑</a-button>
            <a-button type="link" danger @click="del(record.id)" v-has="{ a: $route, b: 2 }">删除</a-button>
          </template>
        </a-table>
      </a-col>
    </a-row>

    <!-- 编辑部门 -->
    <a-modal :destroyOnClose="true" v-model:visible="visibleDep" :title="title" :footer="null" @cancle="cancleDep">
      <a-form ref="editDepRef" :model="editDepForm" :rules="rules1" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item label="部门" name="departmentName">
          <a-input placeholder="请输入部门名称" v-model:value="editDepForm.departmentName"></a-input>
        </a-form-item>
      </a-form>
      <a-row>
        <a-col :span="4" :offset="8" v-if="title !== '查看管理员'">
          <a-button type="primary" @click="saveDep" class="d-a-center">保存</a-button>
        </a-col>
        <a-col :span="4" :offset="title == '查看管理员' ? 10 : 2">
          <a-button type="info" @click="cancleDep" class="d-a-center">关闭</a-button>
        </a-col>
      </a-row>
    </a-modal>

    <!-- 编辑管理员 -->
    <a-modal :destroyOnClose="true" v-model:visible="visible" :title="title" :footer="null" @cancle="cancle">
      <a-form ref="editRef" :model="editForm" :rules="rules1" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item label="管理员" name="realName">
          <a-input placeholder="请输入管理员" v-model:value="editForm.realName"></a-input>
        </a-form-item>
        <a-form-item label="岗位" name="jobName">
          <a-input placeholder="请输入岗位名称" v-model:value="editForm.jobName"></a-input>
        </a-form-item>
        <a-form-item label="账号" name="account">
          <a-input placeholder="请输入登录手机号" v-model:value="editForm.account"></a-input>
        </a-form-item>
        <a-form-item label="部门" name="departmentId">
          <a-select ref="select" v-model:value="editForm.departmentId" @change="handleChange" placeholder="请选择部门">
            <a-select-option v-for="item in deparmentList" :value="item.id" :key="item.id">{{ item.name }} </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="角色权限" name="roleId">
          <a-select ref="select" v-model:value="editForm.roleId" @change="handleChange" placeholder="请选择角色权限">
            <a-select-option v-for="item in roleList" :value="item.id" :key="item.id">{{ item.name }} </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="账号密码" name="password">
          <a-input placeholder="请输入登入密码" v-model:value="editForm.password"></a-input>
        </a-form-item>
        <a-form-item label="确认密码" name="surepassword">
          <a-input placeholder="请确认密码" v-model:value="editForm.surepassword"></a-input>
        </a-form-item>
      </a-form>
      <a-row>
        <a-col :span="4" :offset="8" v-if="title !== '查看管理员'">
          <a-button type="primary" @click="save" class="d-a-center">保存</a-button>
        </a-col>
        <a-col :span="4" :offset="title == '查看管理员' ? 10 : 2">
          <a-button type="info" @click="cancle" class="d-a-center">关闭</a-button>
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>

<script>
import { reactive, ref, computed, createVNode, toRefs, onMounted } from 'vue'
import { EditOutlined, MinusCircleOutlined } from '@ant-design/icons-vue'
import { useModal } from '@/hooks'
import * as api from '@/api/setting/index'
import { validatorPass1, validtorConfirmPass1, validatorPhone } from '@/assets/js/validate'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'

export default {
  name: 'TeamContent',
  components: {
    EditOutlined,
    MinusCircleOutlined
  },
  emits: ['update:modelValue'],
  setup() {
    const formRef = ref('')
    const data = reactive({
      searchForm: {},
      list: [], //管理员列表
      editForm: {
        isDele: 0
      },
      deparmentList: [], // 部门列表
      roleList: [], // 角色列表
      editDepForm: {},
      visibleDep: false,
      activeDep: 15
    })

    const loading = ref(false)
    const visible = ref(false)
    const editRef = ref('')
    const editDepRef = ref('')
    const title = ref('新增管理员')

    // 分页器
    const page = reactive({
      current: 1,
      pageSize: 10,
      total: 0
    })

    const columns = [
      {
        title: '管理员',
        dataIndex: 'realName',
        className: 'table',
        align: 'center',
        sort: true
      },
      {
        title: '岗位',
        dataIndex: 'jobName',
        className: 'table',
        align: 'center'
      },
      {
        title: '账号',
        dataIndex: 'account',
        className: 'table',
        align: 'center'
      },
      {
        title: '角色权限',
        dataIndex: 'roleName',
        className: 'table',
        align: 'center'
      },
      {
        title: '操作',
        dataIndex: 'operation',
        className: 'table',
        align: 'center',
        fixed: 'right',
        slots: {
          customRender: 'operation'
        }
      }
    ]

    // 表单验证
    const rules1 = {
      realName: [
        {
          required: true,
          message: '请输入',
          trigger: 'blur'
        }
      ],
      jobName: [
        {
          required: true,
          message: '请输入',
          trigger: 'blur'
        }
      ],
      departmentId: [
        {
          required: true,
          message: '请选择'
        }
      ],
      roleId: [
        {
          required: true,
          message: '请选择'
        }
      ],
      account: [
        {
          required: true,
          validator: validatorPhone,
          trigger: 'blur'
        }
      ],
      password: [
        {
          validator: validatorPass1,
          trigger: 'blur'
        }
      ],
      surepassword: [
        {
          validator: validtorConfirmPass1,
          trigger: 'blur'
        }
      ]
    }

    // 分页器配置
    const pagination = computed(() => ({
      current: page.current,
      pageSize: page.pageSize,
      pageSizeOptions: ['10', '20', '30'],
      showTotal: (total, range) => {
        return '共' + total + '条'
      },
      total: page.total,
      showQuickJumper: true,
      showSizeChanger: true
    }))

    // 分页器改变事件
    const handleTableChange = (pagination, filters, sorter) => {
      page.current = pagination.current
      page.pageSize = pagination.pageSize
      init()
    }

    // 查询
    const search = () => {
      formRef.value
        .validate()
        .then(() => {
          page.current = 1
          init()
        })
        .catch(error => {})
    }

    const cancle = () => {
      visible.value = false
    }

    const add = () => {
      rules1.password = [
        {
          required: true,
          message: '请输入',
          trigger: 'blur'
        },
        {
          validator: validatorPass1,
          trigger: 'blur'
        }
      ]
      title.value = '新增管理员'
      visible.value = true
      data.editForm = {}
    }

    const cancleDep = () => {
      data.visibleDep = false
    }

    const addDep = () => {
      title.value = '编辑部门'
      data.editDepForm = {}
      data.visibleDep = true
    }

    const edit = e => {
      initDetail(e)
      title.value = '编辑管理员'
      visible.value = true
      rules1.password = [
        {
          validator: validatorPass1,
          trigger: 'blur'
        }
      ]
    }

    const handleEditDep = item => {
      title.value = '编辑部门'
      data.visibleDep = true
      data.editDepForm = {
        ...item
      }
    }

    const handleDeleteDep = id => {
      const { closeModal } = useModal.confirm({
        title: '确定删除当前部门吗?',
        icon: createVNode(ExclamationCircleOutlined),
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: async () => {
          let res = await api.deleteDeparment({
            id
          })
          initData()
          closeModal()
        }
      })
    }

    const del = id => {
      const { closeModal } = useModal.confirm({
        title: '确定删除当前管理员吗?',
        icon: createVNode(ExclamationCircleOutlined),
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: async () => {
          let res = await api.deleteAdminInfo({
            id
          })
          init()
          closeModal()
        }
      })
    }

    const saveDep = () => {
      editDepRef.value
        .validate()
        .then(async () => {
          let res = await api.editDeparmentInfo(data.editDepForm)
          if (res.success) {
            data.visibleDep = false
            initData()
          }
        })
        .catch(error => {})
    }

    const save = () => {
      editRef.value
        .validate()
        .then(async () => {
          let res = {}
          if (data.editForm.isEdit) {
            res = await api.editAdminInfo(data.editForm)
          } else {
            res = await api.addAdminInfo(data.editForm)
          }
          if (res.success) {
            visible.value = false
            init()
          }
        })
        .catch(error => {})
    }

    const initDetail = async id => {
      let res = await api.adminDetail({
        id
      })
      if (res.success) {
        data.editForm = res.object
        data.editForm.isEdit = true
      }
    }

    const handleActive = index => {
      data.activeDep = index
      init()
    }

    const init = async () => {
      loading.value = true
      let res = await api.adminList({
        pageSize: page.pageSize,
        pageNum: page.current,
        ...data.searchForm,
        departmentId: data.activeDep
      })
      if (res.success) {
        res.object.list.map(el => (el.key = el.id))
        data.list = res.object.list
        page.total = res.object.total
        loading.value = false
      }
    }

    const initData = async () => {
      // 角色列表
      api.roleList().then(r => {
        data.roleList = r.object.list.map(r => {
          r.name = r.roleName
          return r
        })
      })
      // 部门列表
      api.deparmentList().then(r => {
        data.deparmentList = r.object.map(r => {
          r.name = r.departmentName
          return r
        })
      })
    }

    // 初始化数据
    init()
    initData()

    return {
      ...toRefs(data),
      formRef,
      rules1,
      columns,
      loading,
      pagination,
      handleTableChange,
      search,
      edit,
      del,
      editRef,
      editDepRef,
      save,
      cancle,
      add,
      title,
      visible,
      labelCol: {
        style: {
          fontWeight: 'bold',
          width: '100px'
        }
      },
      wrapperCol: {
        offset: 1
      },
      saveDep,
      addDep,
      cancleDep,
      handleDeleteDep,
      handleEditDep,
      handleActive
    }
  }
}
</script>

<style scoped lang="less">
.dep_wrap {
  .active {
    color: #2a9d8f;
    font-weight: 500;
  }

  .dep {
    margin: 10px 4px;
  }
}
</style>
